<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑产品 - ubike</title>
    <link rel="stylesheet" href="../styles/styles-main.css">
    <link rel="stylesheet" href="../styles/modules.css">

    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="../modules/module-loader.js"></script>
    <script src="../modules/core-modules.js"></script>
    <script>
        // 动态加载编辑产品所需模块
        document.addEventListener('DOMContentLoaded', async function() {
            try {
                await moduleLoader.loadModules([
                    ['api-client', '../scripts/api-client.js'],
                    ['navbar-main', '../scripts/navbar-main.js'],
                    ['sidebar-manager', '../scripts/sidebar-manager.js']
                ]);
                
                // 初始化产品编辑页面
                initProductEditPage();
            } catch (error) {
                console.error('模块加载失败:', error);
            }
        });
    </script>
    <style>
        .edit-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 30px 20px;
        }
        
        .edit-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #007bff;
        }
        
        .edit-title {
            font-size: 28px;
            font-weight: bold;
            color: #333;
            margin: 0;
        }
        
        .edit-actions {
            display: flex;
            gap: 15px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-1px);
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-1px);
        }
        
        .edit-form {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .form-section {
            margin-bottom: 40px;
            padding: 25px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }
        
        .form-section h3 {
            margin-bottom: 20px;
            color: #495057;
            font-size: 18px;
            font-weight: 600;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }
        
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
            box-sizing: border-box;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }
        
        .form-control.error {
            border-color: #dc3545;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .loading.active {
            display: block;
        }
        
        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: none;
        }
        
        .error-message-global {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: none;
        }
        
        @media (max-width: 768px) {
            .edit-header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }
            
            .edit-actions {
                width: 100%;
                justify-content: flex-end;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="edit-container">
        <div class="edit-header">
            <h1 class="edit-title">编辑产品</h1>
            <div class="edit-actions">
                <a href="../pages/products.html" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> 返回产品列表
                </a>
                <button type="button" class="btn btn-danger" id="deleteBtn">
                    <i class="fas fa-trash"></i> 删除产品
                </button>
            </div>
        </div>
        
        <div class="success-message" id="successMessage">
            <i class="fas fa-check-circle"></i> 产品保存成功！
        </div>
        
        <div class="error-message-global" id="errorMessage">
            <i class="fas fa-exclamation-circle"></i> 保存失败，请检查表单数据
        </div>
        
        <div class="loading" id="loading">
            <i class="fas fa-spinner fa-spin"></i> 正在保存产品...
        </div>
        
        <form class="edit-form" id="productForm">
            <!-- 产品图片 -->
            <div class="form-section">
                <h3><i class="fas fa-images"></i> 产品图片</h3>
                
                <!-- 主图上传 -->
                <div class="form-group">
                    <label for="main_image">产品主图 *</label>
                    <div class="image-upload-container">
                        <input type="file" id="mainImageUpload" accept="image/*" style="display: none;">
                        <div class="image-preview" id="mainImagePreview" style="width: 300px; height: 200px; border: 2px dashed #ddd; border-radius: 8px; display: flex; align-items: center; justify-content: center; cursor: pointer; margin-bottom: 10px;">
                            <div style="text-align: center; color: #666;">
                                <i class="fas fa-camera" style="font-size: 32px; margin-bottom: 8px;"></i>
                                <div>点击上传主图</div>
                            </div>
                        </div>
                        <input type="text" id="main_image" name="main_image" class="form-control" placeholder="主图URL" required>
                        <div class="error-message" id="main_imageError">主图不能为空</div>
                    </div>
                </div>
                
                <!-- 轮播图管理 -->
                <div class="form-group">
                    <label>轮播图片</label>
                    <div class="carousel-management">
                        <div class="carousel-preview" id="carouselPreview" style="display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap;">
                            <!-- 轮播图预览区域 -->
                        </div>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <input type="file" id="carouselImageUpload" accept="image/*" multiple style="display: none;">
                            <button type="button" class="btn btn-primary" id="addCarouselImage" style="padding: 8px 16px;">
                                <i class="fas fa-plus"></i> 添加图片
                            </button>
                            <span style="color: #666; font-size: 12px;">最多可添加5张图片</span>
                        </div>
                        <input type="hidden" id="carousel_images" name="carousel_images">
                    </div>
                </div>
            </div>
            
            <!-- 基本信息 -->
            <div class="form-section">
                <h3><i class="fas fa-info-circle"></i> 基本信息</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="sku">SKU *</label>
                        <input type="text" id="sku" name="sku" class="form-control" required>
                        <div class="error-message" id="skuError">SKU不能为空</div>
                    </div>
                    <div class="form-group">
                        <label for="model">型号 *</label>
                        <input type="text" id="model" name="model" class="form-control" required>
                        <div class="error-message" id="modelError">型号不能为空</div>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label for="name_zh">中文名称 *</label>
                        <input type="text" id="name_zh" name="name_zh" class="form-control" required>
                        <div class="error-message" id="name_zhError">中文名称不能为空</div>
                    </div>
                    <div class="form-group">
                        <label for="name_en">英文名称 *</label>
                        <input type="text" id="name_en" name="name_en" class="form-control" required>
                        <div class="error-message" id="name_enError">英文名称不能为空</div>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label for="name_de">德文名称</label>
                        <input type="text" id="name_de" name="name_de" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="name_fr">法文名称</label>
                        <input type="text" id="name_fr" name="name_fr" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="name_es">西班牙文名称</label>
                        <input type="text" id="name_es" name="name_es" class="form-control">
                    </div>
                </div>
            </div>
            
            <!-- 价格信息 -->
            <div class="form-section">
                <h3><i class="fas fa-dollar-sign"></i> 价格信息</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="price_usd">美元价格 *</label>
                        <input type="number" id="price_usd" name="price_usd" class="form-control" step="0.01" min="0" required>
                        <div class="error-message" id="price_usdError">美元价格必须大于0</div>
                    </div>
                    <div class="form-group">
                        <label for="price_eur">欧元价格</label>
                        <input type="number" id="price_eur" name="price_eur" class="form-control" step="0.01" min="0">
                    </div>
                    <div class="form-group">
                        <label for="price_gbp">英镑价格</label>
                        <input type="number" id="price_gbp" name="price_gbp" class="form-control" step="0.01" min="0">
                    </div>
                </div>
            </div>
            
            <!-- 描述信息 -->
            <div class="form-section">
                <h3><i class="fas fa-file-alt"></i> 产品描述</h3>
                <div class="form-group">
                    <label for="description_zh">中文描述 *</label>
                    <textarea id="description_zh" name="description_zh" class="form-control" rows="4" required></textarea>
                    <div class="error-message" id="description_zhError">中文描述不能为空</div>
                </div>
                <div class="form-group">
                    <label for="description_en">英文描述 *</label>
                    <textarea id="description_en" name="description_en" class="form-control" rows="4" required></textarea>
                    <div class="error-message" id="description_enError">英文描述不能为空</div>
                </div>
                <div class="form-group">
                    <label for="description_de">德文描述</label>
                    <textarea id="description_de" name="description_de" class="form-control" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="description_fr">法文描述</label>
                    <textarea id="description_fr" name="description_fr" class="form-control" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="description_es">西班牙文描述</label>
                    <textarea id="description_es" name="description_es" class="form-control" rows="3"></textarea>
                </div>
            </div>
            
            <!-- 技术规格 -->
            <div class="form-section">
                <h3><i class="fas fa-cogs"></i> 技术规格</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="frame_material">车架材质</label>
                        <select id="frame_material" name="frame_material" class="form-control">
                            <option value="">选择材质</option>
                            <option value="aluminum">铝合金</option>
                            <option value="carbon">碳纤维</option>
                            <option value="steel">钢架</option>
                            <option value="titanium">钛合金</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="frame_size">车架尺寸</label>
                        <select id="frame_size" name="frame_size" class="form-control">
                            <option value="">选择尺寸</option>
                            <option value="XS">XS (14-15")</option>
                            <option value="S">S (16-17")</option>
                            <option value="M">M (18-19")</option>
                            <option value="L">L (20-21")</option>
                            <option value="XL">XL (22-23")</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="max_weight">最大承重 (kg)</label>
                        <input type="number" id="max_weight" name="max_weight" class="form-control" min="0">
                    </div>
                    <div class="form-group">
                        <label for="wheel_size">轮径尺寸</label>
                        <input type="text" id="wheel_size" name="wheel_size" class="form-control" placeholder="如: 26\"、700C">
                    </div>
                    <div class="form-group">
                        <label for="gears">变速档位</label>
                        <input type="text" id="gears" name="gears" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="brakes">刹车系统</label>
                        <input type="text" id="brakes" name="brakes" class="form-control">
                    </div>
                    <div class="form-group">
                        <label for="weight">重量 (kg)</label>
                        <input type="number" id="weight" name="weight" class="form-control" step="0.1" min="0">
                    </div>
                    <div class="form-group">
                        <label for="color_options">可选颜色</label>
                        <input type="text" id="color_options" name="color_options" class="form-control" placeholder="红色,蓝色,黑色...">
                    </div>
                </div>
            </div>
            
            <!-- 库存管理 -->
            <div class="form-section">
                <h3><i class="fas fa-warehouse"></i> 库存管理</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="stock_domestic">国内仓库存</label>
                        <input type="number" id="stock_domestic" name="stock_domestic" class="form-control" min="0">
                    </div>
                    <div class="form-group">
                        <label for="stock_overseas">海外仓库存</label>
                        <input type="number" id="stock_overseas" name="stock_overseas" class="form-control" min="0">
                    </div>
                    <div class="form-group">
                        <label for="safety_stock">安全库存</label>
                        <input type="number" id="safety_stock" name="safety_stock" class="form-control" min="0" value="10">
                    </div>
                </div>
            </div>
            
            <!-- 产品尺寸 -->
            <div class="form-section">
                <h3><i class="fas fa-ruler-combined"></i> 产品尺寸</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="package_size">包装尺寸 (cm)</label>
                        <input type="text" id="package_size" name="package_size" class="form-control" placeholder="长×宽×高">
                    </div>
                </div>
            </div>
            
            <!-- 物流设置 -->
            <div class="form-section">
                <h3><i class="fas fa-shipping-fast"></i> 物流设置</h3>
                <div class="form-group">
                    <label>支持的物流方式</label>
                    <div style="display: flex; gap: 20px; margin-top: 10px;">
                        <label style="display: flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="shipping_dhl" name="shipping_dhl"> DHL
                        </label>
                        <label style="display: flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="shipping_ups" name="shipping_ups"> UPS
                        </label>
                        <label style="display: flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="shipping_sea" name="shipping_sea"> 海运
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <label for="banned_countries">禁运国家</label>
                    <textarea id="banned_countries" name="banned_countries" class="form-control" rows="3" placeholder="每行一个国家"></textarea>
                </div>
            </div>
            
            <!-- 外贸合规 -->
            <div class="form-section">
                <h3><i class="fas fa-certificate"></i> 外贸合规</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="hs_code">HS编码</label>
                        <input type="text" id="hs_code" name="hs_code" class="form-control" placeholder="8712.00.00">
                    </div>
                    <div class="form-group">
                        <label for="origin">原产地</label>
                        <input type="text" id="origin" name="origin" class="form-control" value="中国">
                    </div>
                </div>
                <div class="form-group">
                    <label>认证信息</label>
                    <div style="display: flex; gap: 20px; margin-top: 10px;">
                        <label style="display: flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="ce_certified" name="ce_certified"> CE认证
                        </label>
                        <label style="display: flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="cpsc_certified" name="cpsc_certified"> CPSC认证
                        </label>
                        <label style="display: flex; align-items: center; gap: 5px;">
                            <input type="checkbox" id="rohs_certified" name="rohs_certified"> RoHS环保
                        </label>
                    </div>
                </div>
            </div>
            
            <!-- 表单操作 -->
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" id="cancelBtn">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" class="btn btn-primary" id="saveBtn">
                    <i class="fas fa-save"></i> 保存产品
                </button>
            </div>
        </form>
    </div>

    <script src="products.js"></script>
    <script>
        class ProductEditor {
            constructor() {
                this.productId = null;
                this.originalProduct = null;
                this.init();
            }
            
            init() {
                this.loadProductFromURL();
                this.bindEvents();
                this.setupValidation();
            }
            
            loadProductFromURL() {
                const urlParams = new URLSearchParams(window.location.search);
                const id = urlParams.get('id');
                
                if (!id) {
                    this.showError('缺少产品ID参数');
                    return;
                }
                
                this.productId = parseInt(id);
                this.loadProductData();
            }
            
            loadProductData() {
                if (!window.productManager) {
                    setTimeout(() => this.loadProductData(), 100);
                    return;
                }
                
                const product = window.productManager.products.find(p => p.id === this.productId);
                
                if (!product) {
                    this.showError('产品不存在');
                    return;
                }
                
                this.originalProduct = JSON.parse(JSON.stringify(product));
                this.populateForm(product);
            }
            
            populateForm(product) {
                // 填充所有表单字段
                Object.keys(product).forEach(key => {
                    const element = document.getElementById(key);
                    if (element) {
                        if (key === 'carousel_images' && Array.isArray(product[key])) {
                            element.value = JSON.stringify(product[key]);
                            this.populateCarouselImages(product[key]);
                        } else if (key === 'main_image') {
                            element.value = product[key] || '';
                            if (product[key]) {
                                this.updateMainImagePreview(product[key], document.getElementById('mainImagePreview'));
                            }
                        } else if (key === 'certifications' && Array.isArray(product[key])) {
                            // 处理认证信息复选框
                            if (product[key].includes('ce')) {
                                document.getElementById('ce_certified').checked = true;
                            }
                            if (product[key].includes('cpsc')) {
                                document.getElementById('cpsc_certified').checked = true;
                            }
                            if (product[key].includes('rohs')) {
                                document.getElementById('rohs_certified').checked = true;
                            }
                        } else if (key === 'shipping_methods' && Array.isArray(product[key])) {
                            // 处理物流方式复选框
                            if (product[key].includes('dhl')) {
                                document.getElementById('shipping_dhl').checked = true;
                            }
                            if (product[key].includes('ups')) {
                                document.getElementById('shipping_ups').checked = true;
                            }
                            if (product[key].includes('sea')) {
                                document.getElementById('shipping_sea').checked = true;
                            }
                        } else if (key === 'banned_countries' && Array.isArray(product[key])) {
                            // 处理禁运国家
                            element.value = product[key].join('\n');
                        } else {
                            element.value = product[key] || '';
                        }
                    }
                });
                
                // 更新页面标题
                document.querySelector('.edit-title').textContent = `编辑产品 - ${product.name_zh}`;
            }
            
            populateCarouselImages(images) {
                const previewElement = document.getElementById('carouselPreview');
                previewElement.innerHTML = '';
                
                if (Array.isArray(images)) {
                    images.forEach(imageUrl => {
                        this.addCarouselImage(imageUrl, previewElement);
                    });
                }
            }
            
            bindEvents() {
                document.getElementById('productForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.saveProduct();
                });
                
                document.getElementById('cancelBtn').addEventListener('click', () => {
                    if (this.hasChanges()) {
                        if (confirm('您有未保存的更改，确定要取消吗？')) {
                            window.location.href = 'products.html';
                        }
                    } else {
                        window.location.href = 'products.html';
                    }
                });
                
                document.getElementById('deleteBtn').addEventListener('click', () => {
                    this.deleteProduct();
                });
                
                // 实时验证
                document.querySelectorAll('.form-control').forEach(input => {
                    input.addEventListener('blur', () => {
                        this.validateField(input);
                    });
                    input.addEventListener('input', () => {
                        this.clearError(input);
                    });
                });
                
                // 图片上传功能
                this.setupImageUpload();
            }
            
            setupValidation() {
                this.validators = {
                    sku: (value) => value.trim() !== '',
                    model: (value) => value.trim() !== '',
                    name_zh: (value) => value.trim() !== '',
                    name_en: (value) => value.trim() !== '',
                    price_usd: (value) => parseFloat(value) > 0,
                    description_zh: (value) => value.trim() !== '',
                    description_en: (value) => value.trim() !== '',
                    main_image: (value) => value.trim() !== ''
                };
            }
            
            setupImageUpload() {
                // 主图上传
                const mainImageUpload = document.getElementById('mainImageUpload');
                const mainImagePreview = document.getElementById('mainImagePreview');
                const mainImageInput = document.getElementById('main_image');
                
                mainImagePreview.addEventListener('click', () => {
                    mainImageUpload.click();
                });
                
                mainImageUpload.addEventListener('change', (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        this.handleImageUpload(file, mainImagePreview, mainImageInput);
                    }
                });
                
                // 轮播图上传
                const carouselImageUpload = document.getElementById('carouselImageUpload');
                const addCarouselImageBtn = document.getElementById('addCarouselImage');
                const carouselPreview = document.getElementById('carouselPreview');
                
                addCarouselImageBtn.addEventListener('click', () => {
                    carouselImageUpload.click();
                });
                
                carouselImageUpload.addEventListener('change', (e) => {
                    const files = Array.from(e.target.files);
                    if (files.length > 0) {
                        this.handleCarouselUpload(files, carouselPreview);
                    }
                });
                
                // 主图URL输入变化
                mainImageInput.addEventListener('input', () => {
                    const url = mainImageInput.value.trim();
                    if (url) {
                        this.updateMainImagePreview(url, mainImagePreview);
                    }
                });
            }
            
            handleImageUpload(file, previewElement, inputElement) {
                if (!file.type.startsWith('image/')) {
                    this.showError('请选择图片文件');
                    return;
                }
                
                if (file.size > 5 * 1024 * 1024) {
                    this.showError('图片大小不能超过5MB');
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = (e) => {
                    const imageUrl = e.target.result;
                    this.updateMainImagePreview(imageUrl, previewElement);
                    inputElement.value = imageUrl;
                };
                reader.readAsDataURL(file);
            }
            
            updateMainImagePreview(imageUrl, previewElement) {
                previewElement.innerHTML = `
                    <img src="${imageUrl}" alt="产品主图" style="width: 100%; height: 100%; object-fit: cover; border-radius: 6px;">
                    <div style="position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,0.7); color: white; padding: 2px 5px; border-radius: 3px; font-size: 12px; cursor: pointer;" onclick="event.stopPropagation(); this.closest('.image-preview').innerHTML = '<i class=\"fas fa-camera\" style=\"font-size: 32px; margin-bottom: 8px;\"></i><div>点击上传主图</div>'; document.getElementById('main_image').value = '';">
                        <i class="fas fa-trash"></i>
                    </div>
                `;
            }
            
            handleCarouselUpload(files, previewElement) {
                const currentImages = this.getCurrentCarouselImages();
                const maxImages = 5;
                
                if (currentImages.length + files.length > maxImages) {
                    this.showError(`最多只能添加${maxImages}张轮播图`);
                    return;
                }
                
                files.forEach(file => {
                    if (!file.type.startsWith('image/')) {
                        this.showError('请选择图片文件');
                        return;
                    }
                    
                    if (file.size > 5 * 1024 * 1024) {
                        this.showError('图片大小不能超过5MB');
                        return;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const imageUrl = e.target.result;
                        this.addCarouselImage(imageUrl, previewElement);
                    };
                    reader.readAsDataURL(file);
                });
            }
            
            addCarouselImage(imageUrl, previewElement) {
                const imageId = Date.now();
                const imageElement = document.createElement('div');
                imageElement.className = 'carousel-image-item';
                imageElement.style.cssText = `
                    position: relative;
                    width: 120px;
                    height: 90px;
                    border-radius: 6px;
                    overflow: hidden;
                    border: 2px solid #e9ecef;
                `;
                
                imageElement.innerHTML = `
                    <img src="${imageUrl}" alt="轮播图" style="width: 100%; height: 100%; object-fit: cover;">
                    <div style="position: absolute; top: 2px; right: 2px; background: rgba(0,0,0,0.7); color: white; padding: 2px 4px; border-radius: 3px; font-size: 10px; cursor: pointer;" onclick="this.closest('.carousel-image-item').remove();">
                        <i class="fas fa-times"></i>
                    </div>
                    <div style="position: absolute; bottom: 2px; left: 2px; background: rgba(0,0,0,0.7); color: white; padding: 1px 4px; border-radius: 3px; font-size: 10px; cursor: move;" class="drag-handle">
                        <i class="fas fa-arrows-alt"></i>
                    </div>
                `;
                
                previewElement.appendChild(imageElement);
                this.updateCarouselImagesInput();
            }
            
            getCurrentCarouselImages() {
                const previewElement = document.getElementById('carouselPreview');
                const images = [];
                previewElement.querySelectorAll('img').forEach(img => {
                    images.push(img.src);
                });
                return images;
            }
            
            updateCarouselImagesInput() {
                const images = this.getCurrentCarouselImages();
                document.getElementById('carousel_images').value = JSON.stringify(images);
            }
            
            validateField(input) {
                const fieldName = input.name;
                const value = input.value;
                const validator = this.validators[fieldName];
                
                if (validator && !validator(value)) {
                    this.showFieldError(input, fieldName);
                    return false;
                }
                
                this.clearError(input);
                return true;
            }
            
            showFieldError(input, fieldName) {
                input.classList.add('error');
                const errorElement = document.getElementById(`${fieldName}Error`);
                if (errorElement) {
                    errorElement.style.display = 'block';
                }
            }
            
            clearError(input) {
                input.classList.remove('error');
                const fieldName = input.name;
                const errorElement = document.getElementById(`${fieldName}Error`);
                if (errorElement) {
                    errorElement.style.display = 'none';
                }
            }
            
            validateForm() {
                let isValid = true;
                
                Object.keys(this.validators).forEach(fieldName => {
                    const input = document.querySelector(`[name="${fieldName}"]`);
                    if (input && !this.validateField(input)) {
                        isValid = false;
                    }
                });
                
                return isValid;
            }
            
            hasChanges() {
                if (!this.originalProduct) return false;
                
                const formData = this.getFormData();
                return JSON.stringify(formData) !== JSON.stringify(this.originalProduct);
            }
            
            getFormData() {
                const formData = {};
                const form = document.getElementById('productForm');
                const inputs = form.querySelectorAll('input, textarea, select');
                
                // 收集认证信息
                const certifications = [];
                if (document.getElementById('ce_certified').checked) certifications.push('ce');
                if (document.getElementById('cpsc_certified').checked) certifications.push('cpsc');
                if (document.getElementById('rohs_certified').checked) certifications.push('rohs');
                formData.certifications = certifications;
                
                // 收集物流方式
                const shippingMethods = [];
                if (document.getElementById('shipping_dhl').checked) shippingMethods.push('dhl');
                if (document.getElementById('shipping_ups').checked) shippingMethods.push('ups');
                if (document.getElementById('shipping_sea').checked) shippingMethods.push('sea');
                formData.shipping_methods = shippingMethods;
                
                // 收集禁运国家
                const bannedCountriesInput = document.getElementById('banned_countries');
                formData.banned_countries = bannedCountriesInput.value
                    .split('\n')
                    .map(country => country.trim())
                    .filter(country => country !== '');
                
                // 收集其他字段
                inputs.forEach(input => {
                    if (input.name && !['ce_certified', 'cpsc_certified', 'rohs_certified', 'shipping_dhl', 'shipping_ups', 'shipping_sea'].includes(input.name)) {
                        if (input.type === 'number') {
                            formData[input.name] = parseFloat(input.value) || 0;
                        } else if (input.type === 'checkbox') {
                            formData[input.name] = input.checked;
                        } else {
                            formData[input.name] = input.value;
                        }
                    }
                });
                
                return formData;
            }
            
            saveProduct() {
                if (!this.validateForm()) {
                    this.showError('请检查表单数据');
                    return;
                }
                
                this.showLoading(true);
                
                const formData = this.getFormData();
                
                // 模拟保存延迟
                setTimeout(() => {
                    try {
                        const productIndex = window.productManager.products.findIndex(p => p.id === this.productId);
                        if (productIndex !== -1) {
                            window.productManager.products[productIndex] = {
                                ...window.productManager.products[productIndex],
                                ...formData,
                                updated_at: new Date().toISOString()
                            };
                            
                            window.productManager.saveProducts();
                            this.showSuccess();
                            this.originalProduct = formData;
                        }
                    } catch (error) {
                        this.showError('保存失败：' + error.message);
                    } finally {
                        this.showLoading(false);
                    }
                }, 500);
            }
            
            deleteProduct() {
                if (confirm('确定要删除这个产品吗？此操作不可撤销。')) {
                    window.productManager.deleteProduct(this.productId);
                    window.location.href = 'products.html';
                }
            }
            
            showLoading(show) {
                const loading = document.getElementById('loading');
                const saveBtn = document.getElementById('saveBtn');
                
                if (show) {
                    loading.classList.add('active');
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
                } else {
                    loading.classList.remove('active');
                    saveBtn.disabled = false;
                    saveBtn.innerHTML = '<i class="fas fa-save"></i> 保存产品';
                }
            }
            
            showSuccess() {
                const successMessage = document.getElementById('successMessage');
                successMessage.style.display = 'block';
                
                setTimeout(() => {
                    successMessage.style.display = 'none';
                }, 3000);
            }
            
            showError(message) {
                const errorMessage = document.getElementById('errorMessage');
                errorMessage.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
                errorMessage.style.display = 'block';
                
                setTimeout(() => {
                    errorMessage.style.display = 'none';
                }, 5000);
            }
        }
        
        // 初始化编辑器
        document.addEventListener('DOMContentLoaded', () => {
            if (!window.productManager) {
                window.productManager = new BicycleProductManager();
            }
            new ProductEditor();
        });
    </script>
</body>
</html>